package com.gsbelarus.gedemin.salary.fragment.gdmsg;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.gsbelarus.gedemin.lib.ui.fragment.FragmentModel;
import com.gsbelarus.gedemin.salary.App;
import com.gsbelarus.gedemin.salary.R;
import com.gsbelarus.gedemin.salary.database.RealmHelper;
import com.gsbelarus.gedemin.salary.entity.model.GdMsgModel;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.SnackbarManager;
import com.nispok.snackbar.listeners.ActionClickListener;
import com.nispok.snackbar.listeners.EventListener;

import io.realm.Realm;
import io.realm.RealmResults;

public class GdMsgDetailPagerFragment extends FragmentModel {

    private RealmResults<GdMsgModel> gdMsgs;

    private ViewPager mViewPager;
    private RealmHelper realmHelper;

    private GdMsgModel.Sender senderFilter;
    private String filter;

    private int gdMsgId;
    private boolean isDelete;

    public static GdMsgDetailPagerFragment newInstance() {
        return new GdMsgDetailPagerFragment();
    }

    @Override
    public int getViewResource() {
        return R.layout.gdmsg_detail_pager_fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);

        realmHelper = new RealmHelper(Realm.getInstance(getActivity()));
        gdMsgs = realmHelper.getAllGdMsgs();
    }

    @Override
    public void onCreateViewFragment(View rootView) {
        super.onCreateViewFragment(rootView);

        mViewPager = (ViewPager) rootView.findViewById(R.id.viewPager);
        mViewPager.setClipToPadding(false);
        mViewPager.setPageMargin(40);

        mViewPager.setAdapter(new FragmentStatePagerAdapter(getActivity().getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return GdMsgDetailFragment.newInstance(gdMsgs.get(position));
            }

            @Override
            public int getCount() {
                return gdMsgs.size();
            }

            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }
        });
        mViewPager.clearOnPageChangeListeners();
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                gdMsgId = gdMsgs.get(position).getUid();
                if (gdMsgs.get(position).isUnread())
                    realmHelper.setGdMsgViewedWithSync(gdMsgs.get(position));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void readDataBase() {

    }

    @Override
    public void initView(View rootView) {
        if (mViewPager != null && mViewPager.getAdapter() != null) {

            if (filter != null && !filter.isEmpty())
                gdMsgs = realmHelper.getAllGdMsgs().where()
                        .contains("gdMsgString", filter.toLowerCase(), false).findAllSorted("timestamp", false);
            else
                gdMsgs = realmHelper.getAllGdMsgs();

            if (senderFilter != null) {
                gdMsgs = gdMsgs.where().equalTo("senderIndex", senderFilter.ordinal()).findAllSorted("timestamp", false);
            }

            mViewPager.getAdapter().notifyDataSetChanged();

            for (int i = 0; i < gdMsgs.size(); i++) {
                if (gdMsgs.get(i).getUid() == gdMsgId) {
                    if (gdMsgs.get(i).isUnread())
                        realmHelper.setGdMsgViewedWithSync(gdMsgs.get(i));
                    mViewPager.setCurrentItem(i, false);
                    break;
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        realmHelper.getRealm().close();
        if (mViewPager != null)
            mViewPager.clearOnPageChangeListeners();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_delete:
                if (gdMsgs.size() == 0) return true;

                SnackbarManager.dismiss();
                final int positionForDelete = mViewPager.getCurrentItem();

                SnackbarManager.show(
                        Snackbar.with(getActivity())
                                .text(getResources().getString(R.string.msg_removed) + ".")
                                .actionLabel(getResources().getString(R.string.action_undo))
                                .actionColor(getResources().getColor(R.color.blue))
                                .duration(Snackbar.SnackbarDuration.LENGTH_LONG)
                                .actionListener(new ActionClickListener() {
                                    @Override
                                    public void onActionClicked(Snackbar snackbar) {
                                        isDelete = false;
                                        realmHelper.getRealm().cancelTransaction();
                                        mViewPager.getAdapter().notifyDataSetChanged();
                                        mViewPager.setCurrentItem(positionForDelete);
                                    }
                                })
                                .eventListener(new EventListener() {
                                    @Override
                                    public void onShow(Snackbar snackbar) {
                                        isDelete = true;

                                        realmHelper.getRealm().beginTransaction();
                                        startDeleteByUid(gdMsgs.get(positionForDelete).getUid());

                                        mViewPager.getAdapter().notifyDataSetChanged();
                                    }

                                    @Override
                                    public void onShowByReplace(Snackbar snackbar) {
                                    }

                                    @Override
                                    public void onShown(Snackbar snackbar) {
                                    }

                                    @Override
                                    public void onDismiss(Snackbar snackbar) {
                                        if (isDelete) {
                                            isDelete = false;
                                            realmHelper.getRealm().commitTransaction();
                                        }
                                    }

                                    @Override
                                    public void onDismissByReplace(Snackbar snackbar) {
                                    }

                                    @Override
                                    public void onDismissed(Snackbar snackbar) {
                                    }
                                }));
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void startDeleteByUid(int uid) {
        try {
            GdMsgModel gdMsg = realmHelper.getRealm()
                    .where(GdMsgModel.class).equalTo("uid", uid)
                    .findFirst();
            if (gdMsg != null)
                realmHelper.deleteGdMsgWithSync(gdMsg, false);
        } catch (Exception ex) {
            //Crashlytics.getInstance().core.logException(ex);
            Log.e("my", "startDeleteByUid " + ex.getMessage());
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        SnackbarManager.dismiss();
    }

    @Override
    public void onResume() {
        super.onResume();
        Tracker tracker = ((App) getActivity().getApplication()).getTracker(App.TrackerName.APP_TRACKER);
        tracker.setScreenName(getClass().getSimpleName());
        tracker.send(new HitBuilders.AppViewBuilder().build());
    }

    public int getGdMsgId() {
        return gdMsgId;
    }

    public void setGdMsgId(int gdMsgId) {
        this.gdMsgId = gdMsgId;
    }

    public String getFilter() {
        return filter;
    }

    public void setTextFilter(String filter) {
        this.filter = filter;
    }

    public GdMsgModel.Sender getSenderFilter() {
        return senderFilter;
    }

    public void setSenderFilter(GdMsgModel.Sender senderFilter) {
        this.senderFilter = senderFilter;
    }
}
